'use strict';
const Service = require('egg').Service;
const puppeteer = require('puppeteer');

class Pdf extends Service{
	async create(data){
        const ctx = this.ctx;
        const browser = await puppeteer.launch({args: ['--disable-setuid-sandbox', '--no-sandbox']});
        const page = await browser.newPage();
        let pageSize = data.size ? data.size : 'A4';
        let marginLeft = data.marginLeft ? Number(data.marginLeft) : 20;
        let marginTop = data.marginTop ? Number(data.marginTop) : 20;
        let marginBottom = data.marginBottom ? Number(data.marginBottom) : 20;
        let marginRight = data.marginRight ? Number(data.marginRight) : 20;
        
        await page.goto(data.url, {waitUntil: 'domcontentloaded'}).catch(err => console.log(err));
        await ctx.helper.sleep(2000);
        try {
            let fileName = ctx.helper.generateSecret(10);
            await page.pdf({
                path: './app/public/pdf/' + fileName +'.pdf',
                format: pageSize,
                printBackground: true,  //打印背景图和背景色
                '-webkit-print-color-adjust': 'exact',
                margin: {
                    top: marginTop,
                    bottom: marginBottom,
                    right: marginRight,
                    left: marginLeft
                },
            });
            return ctx.helper.success({url:'/public/pdf/' + fileName +'.pdf'},"成功");
        } catch (e) {
            return ctx.helper.fail('异常');
        } finally {
            await browser.close();
        }
	}
}
module.exports = Pdf;